import os
import random

import requests
from lxml import etree

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'
}


def pages(index):
    if index > 1:
        page = f'_{index}'
    else:
        page = ''
    url = 'https://pic.netbian.com/4kmeinv/index{}.html'.format(page)
    response = requests.get(url, headers=headers)
    response.encoding = 'gbk'
    etr = etree.HTML(response.text)
    imgs = etr.xpath('//div[@class="slist"]//img')
    for img in imgs:
        name = img.xpath('./@alt')[0]
        href = 'https://pic.netbian.com' + img.xpath('./@src')[0]
        # print(name, href)
        path = f'imgs/{name}.jpg'


def download(path, url):
    req = requests.get(url).content
    with open(path, 'wb') as f:
        f.write(req)


def getvideos(index):
    url = f'http://www.sharenice.net/t-576O5aWz?page={index}'
    response = requests.get(url, headers=headers)

    etr = etree.HTML(response.text)
    li_list = etr.xpath('//div[@class="item-box"]//li//a')
    for item in li_list:
        href = item.xpath('./@href')[0]
        title = item.xpath('./@title')[0]
        path = f'videos/{title}.mp4'
        getvideodetail(href, path)


def getvideodetail(url, title):
    response = requests.get(url, headers=headers)
    etr = etree.HTML(response.text)
    href = etr.xpath('//*[@id="play-video"]/@src')[0]
    try:
        download(title, href)
        print(title, '下载完成！')
    except Exception as e:
        print(e)


def geths(page):
    url = f'https://www.keaitupian.cn/tpk/heisimeinv9690_{page}.html'
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    html = response.text
    etr = etree.HTML(html)
    li_list = etr.xpath('//div[@class="related_posts"]/ul/li//img')
    # print(len(li_list))
    for item in li_list:
        src = item.xpath('./@src')[0]
        title = item.xpath('./@alt')[0]
        print(title, src)
        download(f'hs/{title}.jpg', src)


if __name__ == '__main__':
    for i in range(1, 3):
        print(f'page:{i}')
        geths(i)
# current :10 page
